package Socket_Chat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ChatRoomThread implements Runnable {
	public Socket socket;
	public List<Socket> clientList = new ArrayList<Socket>();
	public String message;
	public int onlineCount;
	public InputStream in;
	public OutputStream out;
	
	public void setSocket(Socket socket){
		this.socket = socket;
		clientList.add(socket);
	}
	
	
	@Override
	public void run() {
		Socket currentSocket = socket;
		while(true) {
			try {
				in = currentSocket.getInputStream();
				int len = 0;
				while(len == 0){
					len = in.available();
				}
				byte[] b = new byte[len];
				in.read(b);
				message = currentSocket.getPort()+" "+new String(b, "utf-8");
				System.out.println(message);
				
				Socket that = null;
				Iterator<Socket> iterator = clientList.iterator();
				while(iterator.hasNext()){
					that = iterator.next();
					if(that != currentSocket) {
						out = that.getOutputStream();
						out.write(message.getBytes());
					}
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
			
			
		}
		
		

	}

}
